/**
 * 65c816.c
 * Primary functionality for the 65c816
 */

#include "65c816.h"
#include "debug.h"

CPUContext CPU;

void initializeCPU( CartridgeInfo* info ) {
    info->resetVector = memRead16NoTrap( RSTVECTOR );
    info->nmiVector   = memRead16NoTrap( NMIVECTOR );

    CPU.PC.PCL    = CPU.resetVector = info->resetVector;
    CPU.nmiVector = info->nmiVector;

    CPU.SP      = 0x0100;
    CPU.DPR     = 0;
    CPU.X.xh    = 0;
    CPU.Y.yh    = 0;
    CPU.PC.PBR  = 0;
    CPU.DBR     = 0;
    CPU.P       = MFLAGMASK | XFLAGMASK | IFLAGMASK;

    CPU.emuFlag = 1;
    CPU.mFlag   = 1;
    CPU.xFlag   = 1;
}

unsigned int cpuExecute(u32 cycles) {
    u8   opCode;
    CPU.cycleCounter = (s32)cycles;

    while(CPU.cycleCounter > 0) {
        opCode = memRead8NoTrap(CPU.PC.PCR);
        opcodeFunction[OPCODEHASH(opCode)]();
    	OPDEBUG(opCode);
    }

    return -CPU.cycleCounter + cycles;
}

